package com.ea.report.controller;

import com.ea.common.SA.pojo.entity.VideoFileMeta;
import com.ea.report.exception.StorageFileNotFoundException;
import com.ea.report.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import com.ea.common.result.Result;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/file")
public class FileDownloadController {
    private final StorageService storageService;

    @Autowired
    public FileDownloadController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/list")
    public List<String> listUploadedFiles() {
        return storageService.loadAll().map(
                        path -> MvcUriComponentsBuilder.fromMethodName(FileDownloadController.class,
                                "serveFile", path.getFileName().toString()).build().toUri().toString())
                .collect(Collectors.toList());
    }

    @GetMapping("/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {

        Resource file = storageService.loadAsResource(filename);

        if (file == null)
            return ResponseEntity.notFound().build();

        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

    @PostMapping("/getUploadedFileURL")
    public Result<String> getUploadedFileURL(@RequestParam("uuid") String uuid)
    {
        VideoFileMeta meta = storageService.getMetaByUUID(uuid);
        if (meta != null) {
            return Result.success(MvcUriComponentsBuilder.fromMethodName(FileDownloadController.class,
                    "serveFile", meta.localFileName).build().toUri().toString());
        }
        return Result.fail(1, "Fail to get meta of " + uuid);
    }

    @PostMapping("/getUploadedFileMeta")
    public Result<VideoFileMeta> getUploadedFileMeta(@RequestParam("uuid") String uuid)
    {
        VideoFileMeta meta = storageService.getMetaByUUID(uuid);
        if (meta != null) {
            return Result.success(meta);
        }
        return Result.fail(1, "Fail to get meta of " + uuid);
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }
}
